using System;
using System.ComponentModel;
using Rhino.Commons;

namespace WineCellar.Core.Converters
{
    public class EntityConverter<T> :TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }

            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value.GetType() == typeof(string))
            {
                if (String.IsNullOrEmpty((string)value))
                {
                    return null;
                }
                int id;                
                if (int.TryParse((string)value,out id))
                if (id <= 0)
                {
                    return null;
                }
                return Repository<T>.Get(id);
            }
            return base.ConvertFrom(context, culture, value);
        }
    }
}